package com.ease.framework {

import flash.display.DisplayObject;
import flash.events.Event;

/**
 * A set of utility methods associated with the framework objects.
 */
public class FrinjeUtil
{
   /**
    * @private
    *
    * Returns the event bus associated with the given object, if there is one and it can
    * be looked up through one of the registries in the framework.
    */
   public static function getAssociatedEventBus( object:Object ):EventBus {
      if (object == null) {
         return null;
      }
      if (object is Event) {
         var event:Event = Event( object );
         if (event.target is EventBus) {
            return EventBus( event.target );
         }
         return null;
      }
      var view:DisplayObject = object as DisplayObject;
      if (view == null) {
         view = ViewRegistry.getViewFromMediator( object );
      }
      if (view != null) {
         var viewRegistry:ViewRegistry =
               ViewRegistry.getRegistry( DisplayObject( object ) );
         if (viewRegistry != null) {
            return viewRegistry.eventBus;
         }
      }
      return null;
   }

   /**
    * Returns the original dispatcher of the given event. This is useful in case
    * the event has been re-dispatched through an event bus.
    *
    * @param event
    *    The event which dispatcher to return.
    *
    * @return
    *    The dispatcher (event.target) of the original event in case the event has been
    *    re-dispatched through an event bus. Otherwise event.target of the given event
    *    is returned.
    */
   public static function getOriginalEventDispatcher(event:Event):Object {
      var eventBus:EventBus = FrinjeUtil.getAssociatedEventBus(event);
      if (eventBus != null) {
         var originalEvent:Event = eventBus.originalFromRedispatchedEvent(event);
         return originalEvent.target;
      }

      return event.target;
   }
} // class

}